package hello;

import org.hibernate.Session;

import persistence.HibernateUtil;
import auction.chapter12.CategoryChapter12;

/**
 * Chapter12 Modifying Object Efficiently
 * @author Wei Sun
 *
 */
public class HelloWorldModifyingObjectEfficiently {
	
	public static void main(String[] args) throws Exception {
		//testSaveUpdateCascadeInSessionScope();
		testSaveUpdateCascadeDetached();
	}
	
	public static void testSaveUpdateCascadeDetached() throws Exception{
		
		
		Session s3=HibernateUtil.getSessionFactory().openSession();
		s3.beginTransaction();
		
		//detachedF need fully initialized
		CategoryChapter12 detachedF=(CategoryChapter12)s3.get(CategoryChapter12.class, 1L);
		detachedF.getChildCategories().size();
		s3.getTransaction().commit();
		s3.close();
		
		CategoryChapter12 son2=new CategoryChapter12("son2");
		detachedF.addSon(son2);
		detachedF.setName("father updated");
		
		Session s4=HibernateUtil.getSessionFactory().openSession();
		s4.beginTransaction();
		
		s4.saveOrUpdate(detachedF);
		
		s4.getTransaction().commit();
		s4.close();
	}
	
	public static void testSaveUpdateCascadeInSessionScope() throws Exception{
		
		Session s2=HibernateUtil.getSessionFactory().openSession();
		s2.beginTransaction();
		
		CategoryChapter12 father=new CategoryChapter12("father");
		CategoryChapter12 son1=new CategoryChapter12("son1");
		father.addSon(son1);
		//s2.save(father);
		s2.getTransaction().commit();
		s2.close();
		
		
		Session s3=HibernateUtil.getSessionFactory().openSession();
		s3.beginTransaction();
		
		CategoryChapter12 loadedF=(CategoryChapter12)s3.load(CategoryChapter12.class, 1L);
		CategoryChapter12 son2=new CategoryChapter12("son2");
		//loadedF.getChildCategories();//Hit DB, cause father loaded
		//loadedF.getChildCategories().size();//Hit DB, cause childs loaded
		loadedF.addSon(son2);
		s3.getTransaction().commit();
		s3.close();
	}
	
	public static void getParent(Class clazz) {
		Class parent = clazz.getSuperclass();
		if (parent != null) {
			System.out.println("###" + parent.getName());
			getParent(parent);
		}
	}

	static void out(Object obj) {
		System.out.println("--->" + obj);
	}
}
